package cn.xiaye.blog.dao;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import cn.xiaye.blog.bean.Message;
import cn.xiaye.blog.db.util.DbUtil;

public class MessageDao {
	DbUtil dbUtil = DbUtil.getDefaultDatabaseUtil();

	

	public void insertMessage(Message message) {
		PreparedStatement ps = null;
		ps = dbUtil.prepareStatement("insert into message(text,name,article_id )values(?,?,?)");
		try {
			ps.setString(1, message.getText());
			ps.setString(2, message.getName());
			ps.setInt(3, message.getArticleId());
			ps.executeUpdate();
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			dbUtil.close(ps);
		}
	}

	public void deleteMessage(int messageId) {
		PreparedStatement ps = null;
		ps = dbUtil.prepareStatement("delete from message where id = ?");
		try {
			ps.setInt(1, messageId);
			ps.executeUpdate();
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			dbUtil.close(ps);
		}
	}

	public void updateMessage() {
		PreparedStatement ps = null;
		ps = dbUtil.prepareStatement("");
		try {
			ps.executeUpdate();
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			dbUtil.close(ps);
		}
	}

	public List<Message> queryAll() {
		List<Message> messageList = new ArrayList<Message>();
		PreparedStatement ps = null;
		ps = dbUtil.prepareStatement("select * from message");
		ResultSet rs = null;
		try {
			rs = ps.executeQuery();
			while (rs.next()) {
				Message message = new Message();
				message.setId(rs.getInt("id"));
				message.setText(rs.getString("text"));
				message.setName(rs.getString("name"));
				message.setArticleId(rs.getInt("article_id"));
				messageList.add(message);
			}
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			dbUtil.close(ps);
			dbUtil.close(rs);
		}
		return messageList;

	}
	
	public List<Message> queryByArticleId(int articleId){
		PreparedStatement ps =null;
		ResultSet rs = null;
		List<Message> messageList = new ArrayList<Message>();
		try {
			ps = dbUtil.prepareStatement("select * from message where article_id=?");
			ps.setInt(1, articleId);
			rs = ps.executeQuery();
			while(rs.next()){
				Message message = new Message();
				message.setArticleId(rs.getInt("article_id"));
				message.setId(rs.getInt("id"));
				message.setName(rs.getString("name"));
				message.setText(rs.getString("text"));
				messageList.add(message);
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}finally{
			dbUtil.close(ps);
			dbUtil.close(rs);
		}
		return  messageList;
	}
}
